// pages/familyFeast/menu.js
const app = getApp();
var topOpacity = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    menuTop: app.globalData.menuTop,
    menuList: [],
    chooseMenuId: 0,
    showCarList: false,
    foodList: [],
    carFoodList: [],
    totalNum: 0,
    totalPrice1: 0,
    totalPrice2: 0,
    showSaleDom: false,
    psFee: 0, //配送费
    dbFee: 0, //打包费


    openid: '',
    shareTitle: '',
    shareImg: '',
    bm_time: '', //预约的日期
    yy_time: '', //预约时段 1：午餐  2：晚餐
    topTitleInfo: '', //页面顶部标题信息
    qsMoney: 0, //起送金额
    yhMoney: 0, //优惠明细--优惠金额
    goodsAmount: 0, //优惠明细--商品合计
    yhAmount: 0, //优惠明细--优惠
    is_choose: 0, //是否必选暖心包
    people_number:0,
    mySf:''
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  orderList() {
    wx.navigateTo({
      url: '/pages/familyFeast/orderList',
    })
  },

  //点击去结算
  order() {
    let that = this;
    let carFoodList = that.data.carFoodList;
    if (carFoodList.length == 0) {
      app.showTip("你还没有选择菜品哦~");
      return;
    }

    //判断是否选择了暖心包
    if (that.data.is_choose == 1) {
      //要求暖心包必选
      var tempChoose = 0;
      for (var i = 0; i < carFoodList.length; i++) {
        if (carFoodList[i]['id']==8) { 
          tempChoose = 1;
          break;
        }
      }
      if (tempChoose==0) { 
        app.showTip("您未选必选商品[暖心包],请选择后再去结算哦~");
        return;
      }
    }

    //判断是否到了起送价格
    console.log(that.data.yhAmount - that.data.dbFee);
    if ((that.data.yhAmount - that.data.dbFee) < that.data.qsMoney) {
      app.showTip("抱歉,您订购的菜品暂未达到起送价格哦");
      return;
    }

    //将购物车商品写入缓存中
    wx.setStorageSync('carFoodList', that.data.carFoodList);
    wx.setStorageSync('dbFee', that.data.dbFee);
    wx.setStorageSync('psFee', that.data.psFee);
    wx.setStorageSync('qsMoney', that.data.qsMoney);
    wx.setStorageSync('goodsAmount', that.data.goodsAmount);
    wx.setStorageSync('yhMoney', that.data.yhMoney);
    wx.setStorageSync('yhAmount', that.data.yhAmount);

    wx.navigateTo({
      url: '/pages/familyFeast/settlement?people_number='+that.data.people_number+'&bm_time=' + that.data.bm_time + "&yy_time=" + that.data.yy_time
    });
  },

  //跳转菜谱详情页
  detail(e) {
    var pid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/familyFeast/detail?id=' + pid
    });
  },
  //切换菜谱分类
  changeTab(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    //后台请求菜谱切换
    wx.showLoading({
      title: '菜品切换中...'
    });

    wx.request({
      url: that.data.baseUrl + 'changeFoodList.php',
      method: 'POST',
      data: {
        id: id,
        yy_time: that.data.yy_time,
        carFoodList: JSON.stringify(that.data.carFoodList),
        openid:that.data.openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            chooseMenuId: id,
            foodList: res.data.foodList,
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
        return;
      }
    });

  },
  carList() {
    let that = this;
    let carFoodList = that.data.carFoodList
    if (carFoodList.length == 0) {
      app.showTip("您还没有选择菜品哦~");
      return;
    }
    that.setData({
      showCarList: !that.data.showCarList,
      showSaleDom: false
    })
  },
  closeCarList() {
    this.setData({
      showCarList: false
    })
  },
  closeSaleDom() {
    this.setData({
      showSaleDom: false
    })
  },
  showSaleDom() {
    let that = this;
    let carFoodList = that.data.carFoodList;
    if (carFoodList.length <= 0) {
      app.showTip("您还没有选择菜品哦~");
      return;
    }
    this.setData({
      showSaleDom: !that.data.showSaleDom
    })
  },

  //购物车列表减少商品
  reduce(e) {
    let that = this;
     //判断游客
     if (that.data.mySf == '游客') {
      that.showYkTip();
      return;
    }
    let index = e.currentTarget.dataset.index;
    let carFoodList = that.data.carFoodList;
    let foodList = that.data.foodList;
    let num = carFoodList[index].num;
    let id = carFoodList[index].id;
    let totalNum = 0;
    let totalPrice1 = 0;
    let totalPrice2 = 0;
    num--;
    carFoodList[index].num = num;
    if (num < 1) {
      carFoodList.splice(index, 1);
    }
    let foundObject = foodList.find(item => item.id === id);
    foundObject.num = num;
    carFoodList.forEach(item => {
      totalNum += that.gshNum(item.num);
      totalPrice1 += that.gshNum(item.num) * that.gshNum(item.price1);
      totalPrice2 += that.gshNum(item.num) * that.gshNum(item.price2);
    })
    //如果商品等于0的时候就不加配送费和打包费
    var newTotalPrice1 = 0;
    if (totalPrice1 > 0) {
      newTotalPrice1 = that.gshNum(totalPrice1 + that.data.dbFee + that.data.psFee);
    } else {
      newTotalPrice1 = 0;
    }
    that.setData({
      foodList,
      carFoodList,
      totalNum: that.gshNum(totalNum),
      totalPrice1: newTotalPrice1,
      totalPrice2: that.gshNum(totalPrice2),
      yhMoney: that.gshNum(that.gshNum(totalPrice2) - that.gshNum(totalPrice1)),
      goodsAmount: that.gshNum(totalPrice2 + that.data.dbFee + that.data.psFee),
      yhAmount: that.gshNum(totalPrice1 + that.data.dbFee + that.data.psFee)
    })
  },

  //购物车列表增加商品
  add(e) {
    let that = this;
     //判断游客
     if (that.data.mySf == '游客') {
      that.showYkTip();
      return;
    }
    let index = e.currentTarget.dataset.index;
    let carFoodList = that.data.carFoodList;
    let foodList = that.data.foodList;
    let num = carFoodList[index].num;
    let id = carFoodList[index].id;
    let totalNum = 0;
    let totalPrice1 = 0;
    let totalPrice2 = 0;
    //判断此商品是否达到了单人最高订购数量
    if ((num + 1) > foodList[index].max_yd_number) {
      app.showTip('此商品单人限购' + foodList[index].max_yd_number + '份哦');
      return;
    }

    //判断此商品是否达到了库存上限
    if ((num + 1) > foodList[index].syNum) {
      app.showTip('此商品已达到库存上限了哦');
      return;
    }
    num++;



    carFoodList[index].num = num;
    let foundObject = foodList.find(item => item.id === id);
    foundObject.num = num;
    carFoodList.forEach(item => {
      totalNum += that.gshNum(item.num);
      totalPrice1 += that.gshNum(item.num) * that.gshNum(item.price1);
      totalPrice2 += that.gshNum(item.num) * that.gshNum(item.price2);
    })
    that.setData({
      foodList,
      carFoodList,
      totalNum: that.gshNum(totalNum),
      totalPrice1: that.gshNum(totalPrice1 + that.data.dbFee + that.data.psFee),
      totalPrice2: that.gshNum(totalPrice2),
      yhMoney: that.gshNum(that.gshNum(totalPrice2) - that.gshNum(totalPrice1)),
      goodsAmount: that.gshNum(totalPrice2 + that.data.dbFee + that.data.psFee),
      yhAmount: that.gshNum(totalPrice1 + that.data.dbFee + that.data.psFee)
    })
  },

  //商品列表减少商品
  food_reduce(e) {
    let that = this;
     //判断游客
     if (that.data.mySf == '游客') {
      that.showYkTip();
      return;
    }
    let index = e.currentTarget.dataset.index;
    let foodList = that.data.foodList;
    let carFoodList = that.data.carFoodList;
    let num = foodList[index].num;
    let id = foodList[index].id;
    let totalNum = 0;
    let totalPrice1 = 0;
    let totalPrice2 = 0;
    num--;
    foodList[index].num = num;
    if (num <= 0) {
      let carFoodIndex = carFoodList.findIndex(item => item.id === id);
      if (carFoodIndex !== -1) {
        carFoodList.splice(carFoodIndex, 1); // 删除位于index的元素
      }
    } else {
      let foundObject = carFoodList.find(item => item.id === id);
      foundObject.num = num;
    }
    carFoodList.forEach(item => {
      totalNum += that.gshNum(item.num);
      totalPrice1 += that.gshNum(item.num) * that.gshNum(item.price1);
      totalPrice2 += that.gshNum(item.num) * that.gshNum(item.price2);
    })
    //如果商品等于0的时候就不加配送费和打包费
    var newTotalPrice1 = 0;
    if (totalPrice1 > 0) {
      newTotalPrice1 = that.gshNum(totalPrice1 + that.data.dbFee + that.data.psFee);
    } else {
      newTotalPrice1 = 0;
    }
    that.setData({
      foodList,
      carFoodList,
      totalNum: that.gshNum(totalNum),
      totalPrice1: newTotalPrice1,
      totalPrice2: that.gshNum(totalPrice2),
      yhMoney: that.gshNum(that.gshNum(totalPrice2) - that.gshNum(totalPrice1)),
      goodsAmount: that.gshNum(totalPrice2 + that.data.dbFee + that.data.psFee),
      yhAmount: that.gshNum(totalPrice1 + that.data.dbFee + that.data.psFee)
    })
  },

  //商品列表添加商品
  food_add(e) {
    let that = this;
    //判断游客
    if (that.data.mySf == '游客') {
      that.showYkTip();
      return;
    }

    let index = e.currentTarget.dataset.index;
    let foodList = that.data.foodList;
    let carFoodList = that.data.carFoodList;
    let num = foodList[index].num;
    let id = foodList[index].id;
    let totalNum = 0;
    let totalPrice1 = 0; //折扣价格
    let totalPrice2 = 0; //原价

    //判断此商品是否达到了单人最高订购数量
    if ((num + 1) > foodList[index].max_yd_number) {
      app.showTip('此商品单人限购' + foodList[index].max_yd_number + '份哦');
      return;
    }

    //判断此商品是否达到了库存上限
    if ((num + 1) > foodList[index].syNum) {
      app.showTip('此商品已达到库存上限了哦');
      return;
    }

    num++; //购物车数量加1
    foodList[index].num = num;

    //遍历购物车里的商品是否有跟此次添加的商品id对的上的
    let containsId = carFoodList.some(item => item.id === id);
    if (!containsId) {
      //没得对的上的则往购物车里面添加此商品
      carFoodList.push(foodList[index])
    } else {
      //有对的上的则把购物车数量+1
      let foundObject = carFoodList.find(item => item.id === id);
      foundObject.num = num;
    }
    //充足购物车数组
    carFoodList.forEach(item => {
      totalNum += that.gshNum(item.num);
      totalPrice1 += that.gshNum(item.num) * that.gshNum(item.price1);
      totalPrice2 += that.gshNum(item.num) * that.gshNum(item.price2);
    });

    //console.log(that.data.dbFee);
    //console.log(that.gshNum(totalPrice2 + that.data.dbFee));
    //判断是否第一个商品选了暖心包

    var tempTotalPrice1 = 0;
    if (that.data.carFoodList.length == 1 && foodList[index].id == 8) {
      //第一个商品选择了暖心包
      tempTotalPrice1 = that.gshNum(totalPrice1);
    } else {
      //不是选择了暖心包
      tempTotalPrice1 = that.gshNum(totalPrice1 + that.data.dbFee + that.data.psFee);
    }
    //对所有参数重新赋值
    that.setData({
      foodList, //页面展示的商品
      carFoodList, //购物车商品
      totalNum: that.gshNum(totalNum), //购物车商品总数量
      totalPrice1: tempTotalPrice1, //折扣价总计
      totalPrice2: that.gshNum(totalPrice2), //原价总计
      yhMoney: that.gshNum(that.gshNum(totalPrice2) - that.gshNum(totalPrice1)),
      goodsAmount: that.gshNum(totalPrice2 + that.data.dbFee + that.data.psFee),
      yhAmount: that.gshNum(totalPrice1 + that.data.dbFee + that.data.psFee)
    })
  },

  //处理价格是整型还是浮点型数字
  gshNum(num) {
    if (!isNaN(num) && parseInt(num, 10) === parseFloat(num)) {
      //为整型
      return parseInt(num);
    } else {
      //为浮点型 保留两位小数
      return parseFloat(num).toFixed(2);
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //获取页面参数
    var bm_time = options.bm_time;
    var yy_time = options.yy_time;
    var people_number = options.people_number;
    var mySf = options.mySf;
    //bm_time = '2024-06-28';
    //yy_time=1;

    console.log(bm_time + "********" + yy_time);

    if (mySf!='游客') {
      //参数判断
      if (bm_time == '' || bm_time == undefined) {
        app.showTip('抱歉,未获取到订餐日期哦');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 1400);
        return;
      }

      if (yy_time != 1 && yy_time != 2) {
        app.showTip('抱歉,未获取到订餐时段哦');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 1400);
        return;
      }

      //判断用餐人数
      if (parseInt(people_number) == 0) {
        app.showTip('抱歉,未获取到用餐人数信息哦');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 1400);
        return;
      }

      //保存数据
      that.setData({
        bm_time: bm_time,
        yy_time: yy_time,
        people_number: people_number
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getFamilyFeastMenuPageInfo(res.data.openid, bm_time, yy_time,people_number);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getFamilyFeastMenuPageInfo(openid, bm_time, yy_time,people_number);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getFamilyFeastMenuPageInfo(openid, bm_time, yy_time,people_number) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getFamilyFeastMenuPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        bm_time: bm_time,
        yy_time: yy_time,
        people_number:people_number
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            foodList: res.data.foodList,
            psFee: that.gshNum(res.data.psInfo.ps_money), //配送费
            dbFee: that.gshNum(res.data.psInfo.db_money), //打包费
            topTitleInfo: res.data.topTitleInfo,
            qsMoney: res.data.qsMoney,
            menuList: res.data.menuList,
            is_choose: parseInt(res.data.is_choose),
            mySf:res.data.mySf
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
        return;
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo_order.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  //封装游客提示
  showYkTip() { 
    app.showTip('您还未认证业主身份,请前往个人中心认证后再预定哦');
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    var path = '';
    if (that.data.mySf == '游客') {
      path = '/pages/lifeService/index';
    } else { 
      path = '/pages/familyFeast/index';
    }
    console.log(path);
    return {
      title: that.data.shareTitle,
      path: path,
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})